from django.shortcuts import render, redirect
from app01 import models
from django.core.exceptions import ValidationError
from django import forms

from app01.utils.bootstrapForm import BootstrapModelForm
from app01.utils.pagination import Pagination
from app01.utils.encrypt import md5


class AdminModelForm(BootstrapModelForm):
    """管理员ModelForm"""
    confirmPassword = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True),
    )

    class Meta:
        model = models.Admin
        fields = ['username', 'password', 'confirmPassword']
        widgets = {
            'password': forms.PasswordInput(render_value=True),
        }
    
    def clean_password(self):
        password = self.cleaned_data.get('password')
        encryptedPass = md5(password)
        return encryptedPass

    def clean_confirmPassword(self):
        password = self.cleaned_data['password']
        confirmPassword = self.cleaned_data['confirmPassword']
        if password != md5(confirmPassword):
            raise ValidationError("密码不一致")
        return confirmPassword


class AdminEditModelForm(BootstrapModelForm):
    """编辑管理员ModelForm"""
    class Meta:
        model = models.Admin
        fields = ['username']


class AdminResetModelForm(BootstrapModelForm):
    """重置管理员ModelForm"""
    confirmPassword = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(render_value=True),
    )

    class Meta:
        model = models.Admin
        fields = ['password', 'confirmPassword']
        widgets = {
            'password': forms.PasswordInput(render_value=True),
        }

    def clean_password(self):
        password = self.cleaned_data.get('password')
        encryptedPass = md5(password)
        return encryptedPass

    def clean_confirmPassword(self):
        password = self.cleaned_data.get('password')
        confirmPassword = self.cleaned_data.get('confirmPassword')
        # 不能设置成与之前相同的密码
        exists = models.Admin.objects.filter(id=self.instance.pk, password=password).exists()
        if exists:
            raise ValidationError('密码不能与以前的密码相同！')
        if password != md5(confirmPassword):
            raise ValidationError("密码不一致")
        return confirmPassword


def admin_reset(request, nid):
    """重置管理员密码"""
    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        redirect('/admin/list/')
    title = "重置密码 - {}".format(row_object.username)
    if request.method == 'GET':
        form = AdminResetModelForm()
        return render(request, 'change.html', {'title': title, 'form': form})

    form = AdminResetModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, 'change.html', {'title': title, 'form': form})


def admin_delete(request, nid):
    """删除管理员"""
    row_object = models.Admin.objects.filter(id=nid).exists()
    if row_object:
        models.Admin.objects.filter(id=nid).delete()
    return redirect('/admin/list/')


def admin_edit(request, nid):
    """编辑管理员"""
    title = "编辑管理员"
    row_object = models.Admin.objects.filter(id=nid).first()
    # 以GET方式访问页面
    if request.method == "GET":
        if not row_object:
            return redirect('/admin/list/')
        form = AdminEditModelForm(instance=row_object)
        return render(request, "change.html", {"form": form, "title": title})
    # 以POST方式提交
    form = AdminEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, "change.html", {"form": form, "title": title})


def admin_add(request):
    """添加管理员"""
    title = "新建管理员"
    if request.method == 'GET':
        form = AdminModelForm()
        return render(request, "change.html", {'title': title, 'form': form})

    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/admin/list/')
    return render(request, "change.html", {'title': title, 'form': form})


def admin_list(request):
    """管理员列表"""
    # 获取查询字符串，为空则取空字符串
    query_str = request.GET.get('query_str', '')
    queryset = models.Admin.objects.filter(username__contains=query_str)

    page_object = Pagination(request, queryset)
    html_text = page_object.html
    page_query_set = page_object.page_query_set
    context = {
        'admins': page_query_set,
        'page_html': html_text,
        'query_str': query_str,
    }
    return render(request, 'admin_list.html', context)